package com.geekstudy.week7;

import com.geekstudy.week7.entity.ShopOrder;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Week7Work7 {

    private Connection connection;

    private Statement statement;

    public void init() throws SQLException {
        if(connection == null) {
            String url = "jdbc:mysql://127.0.0.1:3306/geek_java4";
            String username = "java4";
            String password = "java4";
            connection = DriverManager.getConnection(url, username, password);
        }

        if(statement == null) {
            statement = connection.createStatement();
        }
    }

    public List<ShopOrder> queryPage(int pageNumber, int pageSize) throws SQLException {
        List<ShopOrder> shopOrderList = new ArrayList<ShopOrder>();
        if(pageNumber <= 1) {
            pageNumber = 1;
        }
        if(pageSize <= 1) {
            pageSize = 1;
        }
        int startPosition = (pageNumber - 1) * pageSize;
        String querySql = "select * from shop_order order by order_id limit " + startPosition + ", " + pageSize;
        ResultSet resultSet = statement.executeQuery(querySql);
        for(;resultSet.next();) {
            ShopOrder shopOrder = new ShopOrder();
            shopOrder.setOrderId(resultSet.getString("order_id"));
            shopOrder.setOrderUserId(resultSet.getString("order_user_id"));
            shopOrder.setOrderFullPrice(resultSet.getBigDecimal("order_full_price"));
            shopOrder.setOrderDiscountPrice(resultSet.getBigDecimal("order_discount_price"));
            shopOrder.setCreateTime(resultSet.getTimestamp("create_time"));
            shopOrder.setUpdateTime(resultSet.getTimestamp("update_time"));

            shopOrderList.add(shopOrder);
        }

        return shopOrderList;
    }

    public static void main(String[] args) {
        try {
            Week7Work7 work7 = new Week7Work7();

            work7.init();
            List<ShopOrder> shopOrderList = work7.queryPage(109, 8);
            for(ShopOrder  shopOrder: shopOrderList) {
                System.out.println(" orderId:" + shopOrder.getOrderId() + " orderUserId:" + shopOrder.getOrderUserId());
            }


        } catch(Exception e) {
            e.printStackTrace();
        }

    }


}
